/**
 * loans.js - 贷款服务页面脚本
 */

document.addEventListener('DOMContentLoaded', function() {
  // 检查用户登录状态
  if (ApiService.redirectIfNotAuthenticated()) {
    return;
  }
  
  // 初始化组件
  const topNavBar = new TopNavBar();
  topNavBar.init();
  
  const sideBar = new SideBar();
  sideBar.init('loans');
  
  // 初始化贷款相关功能
  initLoanTabs();
  initLoanProducts();
  initLoanRecords();
  initLoanCalculator();
  initLoanApplicationModal();
});

/**
 * 初始化贷款标签页切换
 */
function initLoanTabs() {
  const tabs = document.querySelectorAll('.loan-tab');
  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      // 更新标签页状态
      tabs.forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      
      // 显示对应内容
      const tabId = tab.getAttribute('data-tab');
      document.querySelectorAll('.loan-content').forEach(content => {
        content.classList.remove('active');
      });
      document.getElementById(tabId).classList.add('active');
    });
  });
}

/**
 * 初始化贷款产品列表
 */
function initLoanProducts() {
  const productsList = document.getElementById('loan-products-list');
  
  // 模拟贷款产品数据（实际应从API获取）
  const loanProducts = [
    {
      id: 1,
      title: '个人消费贷款',
      subtitle: '满足您的日常消费需求',
      interestRate: 4.35,
      minAmount: 5000,
      maxAmount: 500000,
      minTerm: 6,
      maxTerm: 36,
      features: [
        '最快1天放款',
        '无需抵押担保',
        '还款方式灵活',
        '提前还款无违约金'
      ]
    },
    {
      id: 2,
      title: '个人住房贷款',
      subtitle: '助您实现安居梦想',
      interestRate: 3.85,
      minAmount: 100000,
      maxAmount: 5000000,
      minTerm: 12,
      maxTerm: 360,
      features: [
        '低利率长期限',
        '首付比例灵活',
        '专业房贷顾问',
        '提供多种还款方式'
      ]
    },
    {
      id: 3,
      title: '个人教育贷款',
      subtitle: '投资未来，成就梦想',
      interestRate: 3.95,
      minAmount: 10000,
      maxAmount: 300000,
      minTerm: 12,
      maxTerm: 60,
      features: [
        '学生专属优惠',
        '在校可申请',
        '毕业后再还款',
        '成绩优秀可减息'
      ]
    },
    {
      id: 4,
      title: '个人经营贷款',
      subtitle: '助力小微创业者',
      interestRate: 4.75,
      minAmount: 50000,
      maxAmount: 2000000,
      minTerm: 12,
      maxTerm: 60,
      features: [
        '创业者专属贷款',
        '手续简便快捷',
        '经营场所可抵押',
        '灵活的还款计划'
      ]
    }
  ];
  
  // 生成产品列表HTML
  let productsHtml = '';
  loanProducts.forEach(product => {
    let featuresHtml = '';
    product.features.forEach(feature => {
      featuresHtml += `
        <div class="loan-product-feature">
          <div class="loan-product-feature-icon">
            <i class="fas fa-check"></i>
          </div>
          <div>${feature}</div>
        </div>
      `;
    });
    
    productsHtml += `
      <div class="loan-product-card" data-id="${product.id}">
        <div class="loan-product-header">
          <div class="loan-product-title">${product.title}</div>
          <div class="loan-product-subtitle">${product.subtitle}</div>
        </div>
        <div class="loan-product-body">
          <div class="loan-product-rate">
            <div class="loan-product-rate-value">${product.interestRate}%</div>
            <div class="loan-product-rate-label">年利率</div>
          </div>
          <div class="loan-product-features">
            ${featuresHtml}
          </div>
          <div class="mb-2">
            <span class="text-muted">贷款金额：</span>
            <span>¥${product.minAmount.toLocaleString()} - ¥${product.maxAmount.toLocaleString()}</span>
          </div>
          <div>
            <span class="text-muted">贷款期限：</span>
            <span>${product.minTerm} - ${product.maxTerm}个月</span>
          </div>
        </div>
        <div class="loan-product-footer">
          <button class="btn btn-primary apply-loan-btn">立即申请</button>
        </div>
      </div>
    `;
  });
  
  productsList.innerHTML = productsHtml;
  
  // 添加申请贷款按钮事件
  document.querySelectorAll('.apply-loan-btn').forEach(button => {
    button.addEventListener('click', (event) => {
      event.preventDefault();
      const productCard = event.target.closest('.loan-product-card');
      const productId = productCard.getAttribute('data-id');
      openLoanApplicationModal(productId);
    });
  });
}

/**
 * 初始化贷款记录列表
 */
function initLoanRecords() {
  const recordsList = document.getElementById('loan-records-list');
  
  // 调用API获取贷款记录
  ApiService.get('/api/loan/list', { page: 1, size: 10 })
    .then(response => {
      if (response.code === 0 && response.data) {
        const records = response.data.list || [];
        renderLoanRecords(records);
      } else {
        throw new Error(response.message || '获取贷款记录失败');
      }
    })
    .catch(error => {
      console.error('获取贷款记录失败:', error);
      recordsList.innerHTML = `
        <div class="empty-state">
          <i class="fas fa-file-alt mb-3" style="font-size: 48px; color: var(--light-text);"></i>
          <p>暂无贷款记录</p>
          <button class="btn btn-primary mt-3" id="start-loan-btn">立即申请贷款</button>
        </div>
      `;
      
      // 添加申请按钮事件
      const startLoanBtn = document.getElementById('start-loan-btn');
      if (startLoanBtn) {
        startLoanBtn.addEventListener('click', () => {
          // 切换到贷款产品标签页
          document.querySelector('.loan-tab[data-tab="loan-products"]').click();
        });
      }
    });
}

/**
 * 渲染贷款记录列表
 * @param {Array} records 贷款记录数组
 */
function renderLoanRecords(records) {
  const recordsList = document.getElementById('loan-records-list');
  
  if (records.length === 0) {
    recordsList.innerHTML = `
      <div class="empty-state">
        <i class="fas fa-file-alt mb-3" style="font-size: 48px; color: var(--light-text);"></i>
        <p>暂无贷款记录</p>
        <button class="btn btn-primary mt-3" id="start-loan-btn">立即申请贷款</button>
      </div>
    `;
    
    // 添加申请按钮事件
    const startLoanBtn = document.getElementById('start-loan-btn');
    if (startLoanBtn) {
      startLoanBtn.addEventListener('click', () => {
        // 切换到贷款产品标签页
        document.querySelector('.loan-tab[data-tab="loan-products"]').click();
      });
    }
    
    return;
  }
  
  let recordsHtml = '';
  records.forEach(record => {
    let statusClass = '';
    switch (record.status) {
      case 0: statusClass = 'pending'; break;
      case 1: statusClass = 'approved'; break;
      case 2: statusClass = 'rejected'; break;
      case 3: statusClass = 'completed'; break;
    }
    
    const applyTime = new Date(record.applyTime).toLocaleDateString();
    const repaymentMethodName = record.repaymentMethod === 1 ? '等额本息' : '等额本金';
    
    recordsHtml += `
      <div class="loan-record-item" data-id="${record.id}">
        <div class="loan-record-header">
          <div class="loan-record-title">
            贷款申请
            <span class="loan-record-status ${statusClass}">${record.statusName}</span>
          </div>
          <div class="loan-record-no">${record.loanNo}</div>
        </div>
        <div class="loan-record-body">
          <div class="loan-record-item-group">
            <div class="loan-record-label">贷款金额</div>
            <div class="loan-record-value">¥${record.amount.toLocaleString()}</div>
          </div>
          <div class="loan-record-item-group">
            <div class="loan-record-label">贷款期限</div>
            <div class="loan-record-value">${record.loanTerm}个月</div>
          </div>
          <div class="loan-record-item-group">
            <div class="loan-record-label">年利率</div>
            <div class="loan-record-value">${record.interestRate}%</div>
          </div>
          <div class="loan-record-item-group">
            <div class="loan-record-label">还款方式</div>
            <div class="loan-record-value">${repaymentMethodName}</div>
          </div>
          <div class="loan-record-item-group">
            <div class="loan-record-label">月还款额</div>
            <div class="loan-record-value">¥${record.monthlyPayment ? record.monthlyPayment.toLocaleString() : '-'}</div>
          </div>
          <div class="loan-record-item-group">
            <div class="loan-record-label">申请日期</div>
            <div class="loan-record-value">${applyTime}</div>
          </div>
          <div class="loan-record-item-group">
            <div class="loan-record-label">贷款用途</div>
            <div class="loan-record-value">${record.purpose || '-'}</div>
          </div>
          <div class="loan-record-item-group">
            <div class="loan-record-label">剩余本金</div>
            <div class="loan-record-value">¥${record.remainingPrincipal ? record.remainingPrincipal.toLocaleString() : '-'}</div>
          </div>
        </div>
        <div class="loan-record-footer">
          <button class="btn btn-outline-primary view-detail-btn" data-id="${record.id}">查看详情</button>
          ${record.status === 1 ? '<button class="btn btn-primary ml-2 repay-loan-btn" data-id="' + record.id + '">还款</button>' : ''}
        </div>
      </div>
    `;
  });
  
  recordsList.innerHTML = recordsHtml;
  
  // 添加详情按钮事件
  document.querySelectorAll('.view-detail-btn').forEach(button => {
    button.addEventListener('click', (event) => {
      event.preventDefault();
      const loanId = button.getAttribute('data-id');
      window.location.href = `/loan-detail.html?id=${loanId}`;
    });
  });
  
  // 添加还款按钮事件
  document.querySelectorAll('.repay-loan-btn').forEach(button => {
    button.addEventListener('click', (event) => {
      event.preventDefault();
      const loanId = button.getAttribute('data-id');
      window.location.href = `/loan-repayment.html?id=${loanId}`;
    });
  });
}

/**
 * 初始化贷款计算器
 */
function initLoanCalculator() {
  const calculateBtn = document.getElementById('calculate-loan');
  const applyLoanBtn = document.getElementById('apply-loan-btn');
  
  calculateBtn.addEventListener('click', calculateLoan);
  applyLoanBtn.addEventListener('click', () => openLoanApplicationModal());
}

/**
 * 计算贷款
 */
function calculateLoan() {
  const amount = parseFloat(document.getElementById('loan-amount').value);
  const term = parseInt(document.getElementById('loan-term').value);
  const rate = parseFloat(document.getElementById('interest-rate').value);
  const method = document.querySelector('input[name="repayment-method"]:checked').value;
  
  if (!amount || amount <= 0) {
    Toast.error('请输入有效的贷款金额');
    return;
  }
  
  // 月利率
  const monthlyRate = rate / 100 / 12;
  
  let monthlyPayment, totalPayment, totalInterest;
  
  if (method === '1') {
    // 等额本息
    monthlyPayment = amount * monthlyRate * Math.pow(1 + monthlyRate, term) / (Math.pow(1 + monthlyRate, term) - 1);
    totalPayment = monthlyPayment * term;
    totalInterest = totalPayment - amount;
  } else {
    // 等额本金
    const monthlyPrincipal = amount / term;
    const firstMonthInterest = amount * monthlyRate;
    const lastMonthInterest = monthlyPrincipal * monthlyRate;
    
    // 首月还款额
    monthlyPayment = monthlyPrincipal + firstMonthInterest;
    
    // 总利息 = (首月利息 + 末月利息) * 期数 / 2
    totalInterest = (firstMonthInterest + lastMonthInterest) * term / 2;
    totalPayment = amount + totalInterest;
  }
  
  // 更新计算结果
  document.getElementById('monthly-payment').textContent = '¥' + monthlyPayment.toFixed(2);
  document.getElementById('total-payment').textContent = '¥' + totalPayment.toFixed(2);
  document.getElementById('total-interest').textContent = '¥' + totalInterest.toFixed(2);
  
  // 显示计算结果
  document.getElementById('loan-calculation-results').style.display = 'grid';
}

/**
 * 初始化贷款申请模态框
 */
function initLoanApplicationModal() {
  const modal = document.getElementById('loan-application-modal');
  const closeBtn = modal.querySelector('.modal-close');
  const prevBtn = document.getElementById('loan-prev-btn');
  const nextBtn = document.getElementById('loan-next-btn');
  const submitBtn = document.getElementById('loan-submit-btn');
  const doneBtn = document.getElementById('loan-done-btn');
  
  // 关闭模态框
  closeBtn.addEventListener('click', () => {
    closeModal();
    resetLoanApplicationForm();
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', (event) => {
    if (event.target === modal) {
      closeModal();
      resetLoanApplicationForm();
    }
  });
  
  // 上一步按钮
  prevBtn.addEventListener('click', () => {
    const activeStep = parseInt(document.querySelector('.loan-step.active').getAttribute('data-step'));
    if (activeStep > 1) {
      goToStep(activeStep - 1);
    }
  });
  
  // 下一步按钮
  nextBtn.addEventListener('click', () => {
    const activeStep = parseInt(document.querySelector('.loan-step.active').getAttribute('data-step'));
    if (activeStep < 3) {
      if (activeStep === 1) {
        if (validateLoanForm()) {
          updateConfirmationStep();
          goToStep(activeStep + 1);
        }
      } else {
        goToStep(activeStep + 1);
      }
    }
  });
  
  // 提交申请按钮
  submitBtn.addEventListener('click', () => {
    if (!document.getElementById('confirm-agreement').checked) {
      Toast.error('请阅读并同意贷款服务协议和个人信息授权书');
      return;
    }
    
    // 获取表单数据
    const formData = new FormData(document.getElementById('loan-application-form'));
    const loanData = {};
    for (const [key, value] of formData.entries()) {
      loanData[key] = value;
    }
    
    // 发送API请求
    ApiService.post('/api/loan/apply', loanData)
      .then(response => {
        if (response.code === 0 && response.data) {
          goToStep(3);
        } else {
          throw new Error(response.message || '申请失败');
        }
      })
      .catch(error => {
        console.error('申请贷款失败:', error);
        Toast.error('申请失败: ' + error.message);
      });
  });
  
  // 完成按钮
  doneBtn.addEventListener('click', () => {
    closeModal();
    resetLoanApplicationForm();
    // 刷新贷款记录
    initLoanRecords();
    // 切换到贷款记录标签页
    document.querySelector('.loan-tab[data-tab="loan-records"]').click();
  });
}

/**
 * 关闭模态框
 */
function closeModal() {
  const modal = document.getElementById('loan-application-modal');
  modal.style.display = 'none';
  console.log('Modal hidden');
}

/**
 * 打开贷款申请模态框
 * @param {string} productId 贷款产品ID（可选）
 */
function openLoanApplicationModal(productId) {
  const modal = document.getElementById('loan-application-modal');
  
  // 如果有产品ID，预先填充产品信息
  if (productId) {
    // 这里应该根据产品ID获取产品信息并填充表单
    // 实际开发中需要从API获取产品详细信息
  }
  
  // 重置表单到第一步
  resetLoanApplicationForm();
  
  // 从计算器复制数据（如果有）
  if (document.getElementById('loan-calculation-results').style.display === 'grid') {
    const amount = document.getElementById('loan-amount').value;
    const term = document.getElementById('loan-term').value;
    const method = document.querySelector('input[name="repayment-method"]:checked').value;
    
    document.getElementById('app-loan-amount').value = amount;
    document.getElementById('app-loan-term').value = term;
    document.querySelector(`input[name="repaymentMethod"][value="${method}"]`).checked = true;
  }
  
  // 显示模态框
  modal.style.display = 'block';
  
  console.log('Modal displayed');
}

/**
 * 重置贷款申请表单
 */
function resetLoanApplicationForm() {
  // 重置表单数据
  document.getElementById('loan-application-form').reset();
  
  // 重置步骤
  goToStep(1);
  
  // 重置确认复选框
  document.getElementById('confirm-agreement').checked = false;
}

/**
 * 跳转到指定步骤
 * @param {number} step 步骤序号（1-3）
 */
function goToStep(step) {
  // 更新步骤状态
  document.querySelectorAll('.loan-step').forEach(stepEl => {
    const stepNumber = parseInt(stepEl.getAttribute('data-step'));
    
    stepEl.classList.remove('active', 'completed');
    if (stepNumber === step) {
      stepEl.classList.add('active');
    } else if (stepNumber < step) {
      stepEl.classList.add('completed');
    }
  });
  
  // 显示当前步骤内容
  document.querySelectorAll('.loan-step-content').forEach(content => {
    content.classList.remove('active');
    if (content.getAttribute('data-step') === step.toString()) {
      content.classList.add('active');
    }
  });
  
  // 更新按钮状态
  const prevBtn = document.getElementById('loan-prev-btn');
  const nextBtn = document.getElementById('loan-next-btn');
  const submitBtn = document.getElementById('loan-submit-btn');
  const doneBtn = document.getElementById('loan-done-btn');
  
  prevBtn.style.display = step > 1 ? 'inline-block' : 'none';
  nextBtn.style.display = step < 2 ? 'inline-block' : 'none';
  submitBtn.style.display = step === 2 ? 'inline-block' : 'none';
  doneBtn.style.display = step === 3 ? 'inline-block' : 'none';
}

/**
 * 验证贷款申请表单
 * @returns {boolean} 验证结果
 */
function validateLoanForm() {
  const amount = parseFloat(document.getElementById('app-loan-amount').value);
  
  if (!amount || amount < 1000 || amount > 1000000) {
    Toast.error('贷款金额必须在1,000元到1,000,000元之间');
    return false;
  }
  
  return true;
}

/**
 * 更新确认信息步骤的内容
 */
function updateConfirmationStep() {
  const amount = parseFloat(document.getElementById('app-loan-amount').value);
  const term = parseInt(document.getElementById('app-loan-term').value);
  const purpose = document.getElementById('app-loan-purpose').value;
  const repaymentMethod = document.querySelector('input[name="repaymentMethod"]:checked').value;
  
  // 显示在确认页面
  document.getElementById('confirm-loan-amount').textContent = '¥' + amount.toLocaleString();
  document.getElementById('confirm-loan-term').textContent = term + '个月';
  document.getElementById('confirm-loan-purpose').textContent = purpose;
  document.getElementById('confirm-repayment-method').textContent = repaymentMethod === '1' ? '等额本息' : '等额本金';
  
  // 计算还款相关信息
  const interestRate = 4.35; // 默认年利率
  const monthlyRate = interestRate / 100 / 12;
  
  document.getElementById('confirm-interest-rate').textContent = interestRate + '%';
  
  let monthlyPayment, totalPayment, totalInterest;
  
  if (repaymentMethod === '1') {
    // 等额本息
    monthlyPayment = amount * monthlyRate * Math.pow(1 + monthlyRate, term) / (Math.pow(1 + monthlyRate, term) - 1);
    totalPayment = monthlyPayment * term;
    totalInterest = totalPayment - amount;
  } else {
    // 等额本金
    const monthlyPrincipal = amount / term;
    const firstMonthInterest = amount * monthlyRate;
    
    // 首月还款额
    monthlyPayment = monthlyPrincipal + firstMonthInterest;
    
    // 总利息（简化计算）
    totalInterest = amount * monthlyRate * (term + 1) / 2;
    totalPayment = amount + totalInterest;
  }
  
  document.getElementById('confirm-monthly-payment').textContent = '¥' + monthlyPayment.toFixed(2);
  document.getElementById('confirm-total-payment').textContent = '¥' + totalPayment.toFixed(2);
  document.getElementById('confirm-total-interest').textContent = '¥' + totalInterest.toFixed(2);
}
